package com.quanxiaoha.weblog.admin.controller;

import com.quanxiaoha.weblog.admin.utils.AliOssUtil;
import com.quanxiaoha.weblog.common.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @description: TODO
 **/
@RestController
@RequestMapping("/admin")
@Slf4j
public class AdminFileController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/file/upload")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Response uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        log.info("文件上传: {}", file.getOriginalFilename());

        // 获取文件扩展名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 生成唯一文件名
        String objectName = UUID.randomUUID().toString() + extension;

        // 上传文件
        String fileUrl = aliOssUtil.upload(file.getBytes(), objectName);

        return Response.success(fileUrl);
    }
    }
